﻿using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;


namespace LdtJudge.DataEngine.Data
{
    /// <summary>
    /// sql帮助类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class SqlCommonUtil<T> where T : new()
    {
        /// <summary>
        /// 是否启用配置中心
        /// </summary>
        private static bool IsLoadLocalDataConfig = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["IsLoadLocalDataConfig"]);
        /// <summary>
        /// 获取连接字符串LdtElementCenter LdtElementCenter
        /// </summary>
        /// <param name="key">key</param>
        /// <returns>string</returns>
        public static string SqlConnString(string key)
        {
            string connstr = ConfigRetrieval.GetConfigRetrieval.GetConnectionString(key);
          
            return connstr;
        }

        #region datatable转实体/实体转Datable

        
        /// <summary>
        /// 根据datatable填充model
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static List<T> FillModel(DataTable dt)
        {
            
            List<T> modelList = new List<T>();
            if (dt == null || dt.Rows.Count == 0)
            {
                return modelList;
            }
            foreach (DataRow dr in dt.Rows)
            {
                T model = new T();
                for (int i = 0; i < dr.Table.Columns.Count; i++)
                {
                    PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
                    if (propertyInfo != null && dr[i] != DBNull.Value)
                        propertyInfo.SetValue(model, dr[i].ToString(), null);
                }

                modelList.Add(model);
            }
            if (modelList==null)
            {
                modelList = new List<T>();
            }
            return modelList;
        }

        /// <summary>
        /// dataTabel数据库保存
        /// </summary>
        /// <param name="connectionStr">连接字符串</param>
        /// <param name="dataTableName">表名</param>
        /// <param name="sourceDataTable">datatabe</param>
        /// <param name="batchSize"></param>
        public static void SqlBulkCopyByDataTable(string connectionStr, string dataTableName, DataTable sourceDataTable, int batchSize = 100000)
        {
            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionStr))
            {
                using (System.Data.SqlClient.SqlBulkCopy sqlBulkCopy = new System.Data.SqlClient.SqlBulkCopy(connectionStr,
                System.Data.SqlClient.SqlBulkCopyOptions.UseInternalTransaction))
                {
                    try
                    {
                        sqlBulkCopy.DestinationTableName = dataTableName;
                        sqlBulkCopy.BatchSize = batchSize;
                        for (int i = 0; i < sourceDataTable.Columns.Count; i++)
                        {
                            sqlBulkCopy.ColumnMappings.Add(sourceDataTable.Columns[i].ColumnName, sourceDataTable.Columns[i].ColumnName);
                        }
                        sqlBulkCopy.WriteToServer(sourceDataTable);
                    }
                    catch (Exception ex)
                    {

                        throw ex;
                    }
                }
            }
        }

        #endregion

        #region 根据实体添加数据



        /// <summary>
        /// Insert SQL语句
        /// </summary>
        /// <param name="t">要转换的对象，不可空</param>
        /// <param name="tableName">要添加的表明，不可空</param>
        /// <returns>
        /// 空
        /// sql语句
        /// </returns>
        //public  bool InsertSqlTabel<T>(T t, string tableName) where T : class
        //{
        //    if (t == null || string.IsNullOrEmpty(tableName))
        //    {
        //        return false;
        //    }
        //    string columns = GetColmons(t);
        //    if (string.IsNullOrEmpty(columns))
        //    {
        //        return false;
        //    }
        //    string values = GetValues(t);
        //    if (string.IsNullOrEmpty(values))
        //    {
        //        return false;
        //    }
        //    StringBuilder sql = new StringBuilder();
        //    sql.Append("Insert into " + tableName);
        //    sql.Append("(" + columns + ")");
        //    sql.Append(" values(" + values + ")");
        //    SqlCmmCommon sqlCmm = new SqlCmmCommon("LdtElementCenter");
        //    string strSql = sql.ToString();
        //    IDbCommand ocmd = sqlCmm.sqhandle.GetSqlHelper.GetCommand(strSql.ToString());
        //    try
        //    {

        //    int re = sqlCmm.sqhandle.GetSqlHelper.ExecuteNonQuery(ocmd);
        //    if (re==0)
        //    {
        //        return false;
        //    }
        //    else
        //    {
        //        return true;
        //    }

        //    }
        //    catch (Exception ex)
        //    {

        //        return false;
        //    }
        //}

        
        /// <summary>
        /// 获得类型的列名
        /// </summary>
        /// <param name="obj">行数据</param>
        /// <returns></returns>
        private static string GetColmons<T>(T obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            return string.Join(",", obj.GetType().GetProperties().Where(p => p.PropertyType.Name.ToLower() == "string").Select(p => p.Name ).ToList());
        }

        /// <summary>
        /// 获得值
        /// </summary>
        /// <param name="obj">行数据</param>
        /// <returns></returns>
        private static string GetValues<T>(T obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            return string.Join(",", obj.GetType().GetProperties().Where(p => p.PropertyType.Name.ToLower() == "string").Select(p => string.Format("'{0}'", p.GetValue(obj))).ToArray());
        }
        #endregion

        #region Dic操作方法

        /// <summary>
        /// dic帮助类
        /// </summary>
        /// <param name="DicData">dic数据</param>
        /// <param name="Key">KEY值</param>
        /// <param name="Value">Value值</param>
        public static Dictionary<string, string> DicValueUtil(Dictionary<string,string> dicData,string key,string value)
        {
            if (dicData.ContainsKey(key))
            {
                dicData[key] = dicData[key] + " and " + value;
            }
            else
            {
                dicData.Add(key, value);
            }
            return dicData;
        }

        #endregion
    }
}
